package com.wiqer.efkv.model.tool;

import com.dyuproject.protostuff.*;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//编译器可能反应不过来
public class SerializationUtils {

    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    private static Objenesis objenesis = new ObjenesisStd();

    private SerializationUtils() {

    }

    /**
     * 序列化(对象 -> 字节数组)
     *
     * @param obj 对象
     * @return 字节数组
     */
    public static <T> byte[] serialize(T obj) {
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(cls);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    /**
     * 反序列化(字节数组 -> 对象)
     *
     * @param data
     * @param cls
     * @param <T>
     */
    public static <T> T deserialize(byte[] data, Class<T> cls) {
        try {
            T message = objenesis.newInstance(cls);
            Schema<T> schema = getSchema(cls);
            ProtostuffIOUtil.mergeFrom(data, message, schema);
            return message;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    public static <T> T deserialize(Input in, Class<T> cls) {
      //  ByteArrayInput input = new ByteArrayInput(data, offset, length, decodeNestedMessageAsGroup);
        try {
            T message = objenesis.newInstance(cls);
            Schema<T> schema = getSchema(cls);
            schema.mergeFrom(in,message);
            return message;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
//    public static <T> int writeTo(LinkedBuffer buffer, T message, com.dyuproject.protostuff.Schema<T> schema) {
//        if (buffer.start != buffer.offset) {
//            throw new IllegalArgumentException("Buffer previously used and had not been reset.");
//        } else {
//            ProtostuffOutput output = new ProtostuffOutput(buffer);
//
//            try {
//                schema.writeTo(output, message);
//            } catch (IOException var5) {
//                throw new RuntimeException("Serializing to a LinkedBuffer threw an IOException (should never happen).", var5);
//            }
//
//            return output.getSize();
//        }
//    }
    private static <T> Schema<T> getSchema(Class<T> cls) {
        Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(cls);
            cachedSchema.put(cls, schema);
        }
        return schema;
    }

}

